export default {
	data() {
		return {
			uploadList: [],
		};
	},
	computed: {
		disableBtn() {
			if(!this.uploadList.length) return false
			return this.uploadList.some(item=>item.status!='success')
		}
	},
	methods: {
			// 删除图片
			deletePic(event) {
				this.uploadList.splice(event.index, 1)
			},
			// 新增图片
			async afterRead(event) {
				// 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
				let lists = Object.prototype.toString.call(event.file) === '[object Array]' ? event.file : [event.file]
				let fileListLen = this.uploadList.length
				try {
					lists.map((item) => {
						this.uploadList.push({
							...item,
							status: 'uploading',
							message: '上传中'
						})
					})
					for (let i = 0; i < lists.length; i++) {
						const result = await this.uploadFilePromise(lists[i]).catch(()=>{
							this.uploadList.splice(fileListLen, 1)
						})
						let item = this.uploadList[fileListLen]
						this.uploadList.splice(fileListLen, 1, Object.assign(item, {
							status: 'success',
							message: '',
							url: result
						}))
						fileListLen++
					}
					this.$forceUpdate()
				} catch (err) {
					this.$utils.showToast(err)
					// this.uploadList = this.uploadList.slice(0, fileListLen)
					console.log(err)
				}
			},
			uploadFilePromise(file) {
				let token = `${uni.getStorageSync('tokenType')} ${uni.getStorageSync('token')}`
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: this.$base.BASE_URL + '/admin/sys-file/upload', //仅为示例，非真实的接口地址
						header: {
							'Authorization': token,
							'Tenant-Id': uni.getStorageSync("tenantId"),
						},
						name: 'file',
						file: file,
						filePath: file.url,
						success: (res) => {
							if (res.data) {
								const data = JSON.parse(res.data)
								if (data.data && data.data.url) {
									resolve(data.data.url)
								} else {
									reject('上传失败')
								}
							} else {
								reject('上传失败')
							}
						},
						fail: (err) => {
							console.log(err)
							reject('上传失败')
						}
					});
				})
			},
	},
}